package by.bsu.rfe.belianko.euniversity.controller.command;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.constants.ErrorMessages;
import by.bsu.rfe.belianko.euniversity.constants.LoggerMessages;
import by.bsu.rfe.belianko.euniversity.constants.PageNames;
import by.bsu.rfe.belianko.euniversity.dao.IFacultiesDAO;
import by.bsu.rfe.belianko.euniversity.exceptions.CommandException;
import by.bsu.rfe.belianko.euniversity.exceptions.DaoTechnicalException;
import by.bsu.rfe.belianko.euniversity.model.DataBaseLayer;
import by.bsu.rfe.belianko.euniversity.model.Faculty;
import by.bsu.rfe.belianko.euniversity.model.Student;

/**
 * Supports students actions.
 * 
 * @author Vitali_Belianko
 * 
 */
public class CabinetCommand implements Command {

	private static final String STUDENT = "student";
	private static final String FACULTY = "faculty";
	private static final String FACULTY_LIST = "facultyList";
	private static final IFacultiesDAO facultiesDao = DataBaseLayer.getFacultiesDAO();
	private static final Logger LOGGER = Logger.getLogger(CabinetCommand.class);

	/**
	 * Load student info from DB.
	 * 
	 * @param request
	 * 
	 * @return cabinet page
	 * @throws CommandException
	 */
	@Override
	public String execute(HttpServletRequest request) throws CommandException {

		LOGGER.debug(LoggerMessages.STARTED_COMMAND);

		List<Faculty> facultyList = null;
		Faculty faculty = null;
		Student studentAttribute = (Student) request.getSession(true).getAttribute(STUDENT);

		try {
			facultyList = facultiesDao.getFacultyList();
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(ErrorMessages.CAN_NOT_GET_LIST_OF_FACULTY, e);
		}
		request.getSession(true).setAttribute(FACULTY_LIST, facultyList);
		long facultyId = studentAttribute.getFaculty().getFacultyId();
		try {
			faculty = facultiesDao.getFacultyById(facultyId);
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(ErrorMessages.CAN_NOT_GET_FACULTY, e);
		}
		request.getSession(true).setAttribute(FACULTY, faculty);

		LOGGER.debug(LoggerMessages.FINISHED_COMMAND);

		return PageNames.CABINET_PAGE;
	}

}
